package core

import (
	"bytes"
	"context"
	hlp "gitee.com/dreamwood/jxgo/v1/helper"
	"net/http"
	"time"
)

type Session struct {
	//链路key
	ChainKey string
	//处理数据输入
	Input *Input
	//处理数据输出
	Output  *Output
	Handler *EzHandler
	//操作计时器
	Timer *Timer
	//是否中止
	IsStop bool

	//日志
	StartAt time.Time
	Logs    []*SessionLog
}

func NewSession(resp http.ResponseWriter, req *http.Request) *Session {
	session := new(Session)
	session.ChainKey = hlp.CreateRandString(64)
	//初始化输入数据
	in := GetInputFromRequest(req)
	session.Input = in
	//初始化输出数据
	out := new(Output)
	out.Response = resp
	bf := bytes.NewBuffer([]byte{})
	out.Writer = bf
	session.Output = out
	//初始化操作计时器
	session.Timer = NewTimer()
	session.IsStop = false

	session.StartAt = time.Now()
	session.Logs = make([]*SessionLog, 0)

	return session
}

func (this *Session) Get(key string) *InputAnyThing {
	return this.Input.Get(key)
}

func (this *Session) GetHeader() http.Header {
	return this.Input.Request.Header
}

func (this *Session) SetHeader(key string, value string) {
	this.Input.Request.Header.Set(key, value)
}

func (this *Session) CreateContext() context.Context {
	return context.WithValue(context.Background(), "session", this)
}

func (this *Session) FillJson(model interface{}) error {
	return json.Unmarshal(this.Input.Json, model)
}

func (this *Session) JsonOut(data interface{}) {
	this.Output.Json(data)
}
func (this *Session) Html(data string) {
	this.Output.Html(data)
}

func (this *Session) Stop() {
	this.IsStop = true
}

func (this *Session) StopHandle() {
	this.Handler.IsStop = true
}

func GetSessionFromContext(ctx context.Context) *Session {
	v := ctx.Value("session")
	find, ok := v.(*Session)
	if ok {
		return find
	} else {
		return nil
	}
}
